package com.example.zkweixiu.app.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonAdapter;
import com.example.zkweixiu.app.R;
import com.example.zkweixiu.app.bean.MangeBean;
import com.example.zkweixiu.app.bean.TaskBean;
import com.example.zkweixiu.app.pro.PublicPro;
import com.google.gson.Gson;
import com.vondear.rxtool.RxActivityTool;
import com.yanzhenjie.sofia.Sofia;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/***
 * 客户管理
 *
 * */
public class UserManageActivity extends AppCompatActivity {
    private SwipeRefreshLayout sw_out;
    int page = 1;

    private Context context;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 200:
                    initView2();

                    if (rows1 == null || rows1.size() == 0) {
                        ll_gone.setVisibility(View.VISIBLE);
                        //      sw_out.setVisibility(View.GONE);
                        //   return;
                    } else {
                        ll_gone.setVisibility(View.GONE);
                        //   sw_out.setVisibility(View.VISIBLE);
                    }

                    list_task.setAdapter(commonAdapter);

                    if (sw_out != null) {
                        if (sw_out.isRefreshing()) {//判断是否下拉刷新状态
                            sw_out.setRefreshing(false);
                            Toast.makeText(context, "刷新完成", Toast.LENGTH_SHORT).show();
                        }
                    }

                    list_task.setOnScrollListener(new AbsListView.OnScrollListener() {  //监听ListView到达底部
                        @Override
                        public void onScrollStateChanged(AbsListView absListView, int i) {

                        }

                        @Override
                        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                            if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                                View lastVisibleItemView = list_task.getChildAt(list_task.getChildCount() - 1);
                                if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == list_task.getHeight()) {
                                    page++;
                                    initDatas(page, 10);
                                    //  Toast.makeText(SonListActivity.this,"到达底部",Toast.LENGTH_SHORT).show();

                                }
                            }

                        }
                    });
                    break;
            }
        }
    };

    private CommonAdapter<MangeBean.DataBean.RowsBean> commonAdapter;
    private LinearLayout ll_gone;
    private ListView list_task;

    private void initView2() {
        /*
         */
        commonAdapter = new CommonAdapter<MangeBean.DataBean.RowsBean>(context, R.layout.task_item3, rows1) {

            @Override
            public void onUpdate(BaseAdapterHelper helper, final MangeBean.DataBean.RowsBean item, final int position) {

                helper.setText(R.id.tv_name, item.getUserName());
                helper.setText(R.id.tv_name1, item.getSetUuid());
                DateTime dateTime = new DateTime();

                if (item.getSetBindTime() == null) {
                    helper.setText(R.id.tv_name3, "暂未获取");
                } else {
                    String s = dateTime.withMillis(item.getSetBindTime()).toString("MM/dd HH:mm");//系统时间格式化
                    helper.setText(R.id.tv_name3, s);

                }

                helper.setOnClickListener(R.id.rl_clke, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent intent = new Intent(context, UserDataActivity.class);
                        startActivity(intent);

                        EventBus.getDefault().postSticky(rows1.get(position));

                    }
                });
            }
        };
    }

    private List<MangeBean.DataBean.RowsBean> rows1 = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_manage);
        Sofia.with(UserManageActivity.this).statusBarDarkFont().statusBarBackground(Color.parseColor("#FFFFFF"));

        RelativeLayout rl_add = findViewById(R.id.rl_add);
        ImageView iv_fanhui = findViewById(R.id.iv_fanhui);
        View iv_fanhui2 = findViewById(R.id.iv_fanhui2);

        rl_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent  intent = new Intent(context, AddUserDataActivity.class);
                startActivity(intent);
            }
        });
        iv_fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        iv_fanhui2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        context = UserManageActivity.this;
        initView();
        initDatas(page, 10);
    }

    /**
     * 网络请求
     */
    private void initDatas(final int page, int rows) {
        Log.e("initDatas", PublicPro.userBean.getData().getGuaToken());
        OkHttpUtils
                .get()
                .url(PublicPro.MANGE_LIST)
                .addParams("wx_uuid", PublicPro.userBean.getData().getGuaUuid()) //获取用户uuid
                .addParams("token", PublicPro.userBean.getData().getGuaToken()) //获取token
                .addParams("page", page + "")
                .addParams("rows", rows + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (sw_out != null) {
                            sw_out.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        if (response.contains("用户过期,请重新登录")) {

                            RxActivityTool.skipActivityAndFinishAll(context, LoginActivity.class);
                            return;

                        }

                        MangeBean mangeBean = new Gson().fromJson(response, MangeBean.class);

                        if (mangeBean.getStatus() == 200) {
                            if (page == 1) {
                                // rows1.clear();
                                rows1 = mangeBean.getData().getRows();
                                //  rows1.addAll(rows1);
                            } else {
                                if (mangeBean.getData().getRows() == null || mangeBean.getData().getRows().size() == 0) {
                                    Toast.makeText(UserManageActivity.this, "没有更多数据了", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                rows1.addAll(mangeBean.getData().getRows());
                            }


                            handler.sendEmptyMessage(200);

                        } else {
                            Toast.makeText(UserManageActivity.this, mangeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                });
    }

    private void initView() {

        sw_out = findViewById(R.id.sw_out);
        ll_gone = findViewById(R.id.ll_gone);
        list_task = (ListView) findViewById(R.id.list_task);

        sw_out.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //
                initDatas(page, 10);
            }
        });

    }


}
